const HandleBlogRouter = require('./src/router/blog')
const HandleUserRouter = require('./src/router/user')
const querystring = require('querystring')
const { get, set } = require('./src/database/redis')

const getCookieExpires = () => {
  let d = new Date()
  d.setTime(d.getDate() + (48 * 60 * 60 * 1000)) //这个意思是重新设置当前的时间开始的过期时间
  return d.toUTCString() //就是cookie格式的时间表示
}
//session
// const SEESION_DATA = {}

const getPostData = (req) => {
  const promise = new Promise((resolve, reject) => {
    if (req.method != 'POST') {
      resolve({})
      return
    }
    if (req.headers['content-type'] !== 'application/json') {
      resolve({})
      return
    }
    let postData = ''
    req.on('data', chunk => {
      postData += chunk.toString()
    })
    req.on('end', () => {
      if (!postData) {
        resolve({})
        return
      }
      resolve(JSON.stringify(postData))///parse


    })

  })
  return promise
}


const serverhandle = (req, res) => {
  res.setHeader('Content-type', 'application/json')
  const url = req.url
  req.path = url.split('?')[0]  //不要重复在blog/user路由里面去写这个path,完全可以在客户端这里去处理路径。
  //挂载到 req上全局上这样以后直接就可以用了
  req.query = querystring.parse(url.split('?')[1])
  //解析cookie
  req.cookie = {}
  const cookiestr = req.headers.cookie || ''

  cookiestr.split(';').forEach(element => {
    if (!element) {
      return
    }
    const arr = element.split('=')
    const key = arr[0].trim()
    const val = arr[1].trim()
    req.cookie[key] = val
  });

  //找cookie与session的对应关系
  // let needSetCookie = false
  // let userId = req.cookie.userid
  // if (userId) {
  //   if (!SEESION_DATA[userId]) {
  //     SEESION_DATA[userId] = {}

  //   }


  // } else {
  //   needSetCookie = true
  //   userId = `${Date.now()}_ ${Math.random()}`
  //   SEESION_DATA[userId] = {}

  // }
  // req.session = SEESION_DATA[userId]

  //解析session (redis)
  let needSetCookie = false
  let userId = req.cookie.userid
  if (!userId) {
    needSetCookie = true
    userId = `${Date.now()}_ ${Math.random()}`
    //初始化redis 里的 session
    set(userId, {})
  }
  // 获取并来设置sessionid
  req.sessionId = userId //我想知道就是这个sessionid和session之间有什么样的区别
  get(req.sessionId).then(sessiondata => {
    if (sessiondata === null) {
      set(req.sessionId, {})
      req.session = {} //这里才是在设置这个session,再理解一下
    } else {
      req.session = sessiondata
    }
    return getPostData(req)//由于之后的任务也是一个promise，所以想通过这个then来实现链式的调用
  }).then(postData => {
    req.body = postData   //以后想获得postdata的数据直接用挂载到body相当于http请求的身体专门用来存放数据也符合实际
    //这里有一个小bug就是用parse错误了应该是用stringfy的
    let resData = HandleBlogRouter(req, res)
    if (resData) {
      console.log(resData);
      resData.then(blogdata => {
        if (needSetCookie) {
          res.setHeader('Set-Cookie', `userid=${userId}; path=/; httpOnly; expires=${getCookieExpires()}`)
        }
        res.end(JSON.stringify(blogdata))
      })
      return
    }


    //user路由处理
    let userdata = HandleUserRouter(req, res)
    if (userdata) {
      userdata.then(usdata => {
        if (needSetCookie) {
          res.setHeader('Set-Cookie', `userid=${userId}; path=/; httpOnly; expires=${getCookieExpires()}`)
        }
        res.end(JSON.stringify(usdata))
      })
      return  //这里是为了防止，已经有值了还继续向后执行

    }


    res.writeHead(404, { "Content-type": "text/plain" })
    res.write("404 Not Found\n")
    res.end()

  })


}
module.exports = serverhandle
//这里是在设置返回头，以及头信息的返回